package chesskers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import menu.GameDisplayPanel;

public class GameTimer {
	private static final int TIMER_PERIOD = 1000;
	private GameDisplayPanel p; // holds a reference to the Welcome class
	private long count1, count2;

	public GameTimer(GameDisplayPanel p) {
		this.p = p; // initializes the reference to the Welcome class.
		p.state.player1.count = 0;
		p.state.player2.count = 0;
		p.profile1Time.setText(Utils.counttoString(p.state.timeLimit));
		p.profile2Time.setText(Utils.counttoString(p.state.timeLimit));
	}

	public void start() {
		new Timer(TIMER_PERIOD, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (p.state.player1.count <= p.state.timeLimit && p.state.player2.count <= p.state.timeLimit) {
					if (!p.state.blackGoing) {
						p.state.player1.count++;
						p.profile1Time.setText(Utils.counttoString(p.state.timeLimit - p.state.player1.count));
					} else {
						p.state.player2.count++;
						p.profile2Time.setText(Utils.counttoString(p.state.timeLimit - p.state.player2.count));
					}
				} else {
					((Timer) e.getSource()).stop();
					if (p.state.player1.count == p.state.player2.count)
						p.Tie();
					else if (p.state.player1.count > p.state.timeLimit) 
						p.Victory(false, false);
					else if (p.state.player2.count > p.state.timeLimit) 
						p.Victory(true, false);
				}
			}
		}).start();
	}
}